﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace MGAS.UI.Controls
{
    public class AutoAlignGroupBox : GroupBox
    {
        private int _count;
        public void SetMaxCount(int count)
        {
            if (_count != 0)
                throw new InvalidOperationException("Already set max control count.");
            _count = count;
        }

        private int _itemPerColumn;
        public void SetItemPerColumn(int itemPerColumn)
        {
            if (_itemPerColumn != 0)
                throw new InvalidOperationException("Already set item per Column.");
            _itemPerColumn = itemPerColumn;
        }

        private int _cols;
        private Dictionary<int, Panel> _pnls;
        public void Initialize(int buttonWidth)
        {
            if (_count == 0 || _itemPerColumn == 0)
                throw new InvalidOperationException("item per column/count not set yet.");

            _pnls = new Dictionary<int, Panel>();

            _cols = _count / _itemPerColumn;
            if (_count % _itemPerColumn != 0)
                _cols++;

            this.Width = buttonWidth * _cols + 4 * _cols;//Refactor:4
            for (int i = 0; i < _cols; i++)
            {
                Panel p = new Panel();
                p.Dock = DockStyle.Right;
                p.Width = buttonWidth;
                this.Controls.Add(p);
                _pnls.Add(i, p);
            }
        }

        private int _actualCount;
        public void AppendControl(Control c)
        {
            if (_actualCount >= _count)
                throw new InvalidOperationException("actual count is overflow.");

            var col = _actualCount / _itemPerColumn;            

            Panel p = _pnls[col];
            c.Dock = DockStyle.Top;
            p.Controls.Add(c);

            _actualCount++;
        }
    }
}
